if(files.cwd().endsWith("脚本")){
  let _require = require;
  require = function(path){
    if(path.startsWith("./")){
      path = path.replace("./","");
    }
    path = files.cwd() + "/gdt_hb/" + path;
    return _require(path);
  }
}


auto.waitFor()
var utils = require("./utils.js");

var storage = storages.create("xiangxiangyuedu");
var time = random(2000, 3000)

function launchAppEnhance(app_name) {
  let thread = threads.start(function () {
    toastLog("检查是否有打开权限!")
    while (true) {
      var allow = text("允许").findOne(5000)
      if (allow) {
        sleep(1000)
        toastLog("发现允许授权!")
        allow.click()
        sleep(1000)
        thread.interrupt()
        break
      }
    }
  })
  sleep(1000)
  var result = launchApp(app_name)
  sleep(3000)
  thread.interrupt()
  return result
}

function task() {
  var 首页 = text('首页').findOne(20000)
  if (首页) {
    sleep(5000)
    var 签到 = id('iv_singe').findOne(5000)
    if (签到) {
      签到.click()
      var 已签到 = text('已签到').findOne(5000)
      if (已签到) {
        toastLog('已签到,任务完成')
        // utils.updateAppProgress(100);
        // sleep(time)
        // return ;
    }  
    var index = 0
    while (index < 12) { //9个视频,12如果找不到去完成则上滑几次
      var 去完成 = text('去完成').findOne(1000)
      if (去完成) {
        var finalActivity = currentActivity();
        去完成.click()
        toastLog('当前是广告界面')
        // 广告(finalActivity)
        utils.waitAdvert(finalActivity);
        sleep(time)
      }else{
        utils.swip_up();
        sleep(time)
      }
      index++
      if(index * 5 < 100){
        utils.updateAppProgress(index * 5);
      }
    }
    var 立即签到 = text('立即签到').findOne(5000)
    log("立即签到:" + 立即签到)
    if (立即签到) {
      立即签到.click()
      
      sleep(time)
      log("签到完成.")
    }
   
  }
 }
}

function main() {
  let open_app = launchAppEnhance("天天赚");
  if (open_app) {
    var thread_1 = threads.start(function () {
      toastLog("检查广告弹窗")
      while (true) {
        var widget = text("知道了").findOne(2000);
        if (widget) {
          widget.click()
        }
      }
    })
    task()
    thread_1.interrupt()
  }
  else {
    toastLog("天天赚打开失败，请确认是否安装并授权打开!");
  }
}

try {
  main();
  utils.updateAppProgress(100);
} catch (error) {
  toastLog(error);
}
storage.put("script_running_status", "end");
